/**
 * @Description: 异步
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 18/12/24 PM2:25
 */
import { to } from 'sf-utils2'

type LoadingCallback = () => Promise<void>

type ServiceCallback = () => Promise<any>

/**
 * 设置最大loading 自动取消
 * @param bootstrapFns
 * @param time
 */
export async function withLoadingMaxTime(bootstrapFns: [ServiceCallback, LoadingCallback?], time?: number) {
  time ??= 30 * 1000 // 默认30s
  let timeoutId
  const [serviceFunc, loadingFunc] = bootstrapFns
  const _timeoutPromise = () =>
    new Promise((_, reject) => {
      timeoutId = setTimeout(async () => {
        await to(loadingFunc?.())
        reject(new TypeError('加载超时'))
      }, time)
    })

  try {
    await Promise.race([serviceFunc?.(), _timeoutPromise()])
  } finally {
    if (timeoutId) clearTimeout(timeoutId)
  }
}
